<template>
  <el-card>
    <div v-if="!parsedData || Object.keys(parsedData).length === 0" class="no-data">
      <el-empty description="暂无检测数据"></el-empty>
    </div>
    <div v-else>
      <!-- 动态渲染字段 -->
      <div v-for="(rowFields, rowIndex) in groupedFields" :key="rowIndex">
        <!-- 分组标题行 -->
        <div v-if="rowFields.length === 1 && rowFields[0].isGroupHeader" class="group-header">
          <el-divider>
            <span :class="['group-title', rowFields[0].colorClass]">
              <i class="el-icon-collection"></i>
              {{ rowFields[0].groupName }}
            </span>
          </el-divider>
        </div>

        <!-- 字段数据行 -->
        <el-row
          v-else
          :gutter="20"
          class="detail-row"
        >
          <el-col
            v-for="field in rowFields"
            :key="field.key"
            :span="field.span || 8"
          >
            <div class="grid-content" :class="field.groupColorClass">
              <span class="field-label">{{ field.label }}:</span>
              <span class="field-value" :class="getValueClass(field, parsedData[field.key])">
                {{ formatValue(field, parsedData[field.key]) }}
              </span>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
  </el-card>
</template>

<script>
import { getFieldConfig } from './fieldConfigs'
import { mapFieldName } from './fieldMapper'

export default {
  name: 'DynamicDetailRenderer',
  props: {
    // JSON字符串或对象
    data: {
      type: [String, Object],
      default: () => ({})
    },
    // 数据类型，用于确定使用哪个配置
    dataType: {
      type: String,
      default: 'auto'
    },
    // 每行显示的字段数量
    fieldsPerRow: {
      type: Number,
      default: 3
    },
    // 是否启用分组排序
    enableGrouping: {
      type: Boolean,
      default: true
    }
  },
  computed: {
    parsedData() {
      if (typeof this.data === 'string') {
        try {
          return JSON.parse(this.data)
        } catch (e) {
          console.error('JSON解析失败:', e)
          return {}
        }
      }
      return this.data || {}
    },

    detectedDataType() {
      if (this.dataType !== 'auto') {
        return this.dataType
      }

      // 自动检测数据类型
      const data = this.parsedData
      if (data.screwCCDcheckResult !== undefined || data.screwCCDResult !== undefined) {
        return 'screw' // 螺丝拧紧类型
      }
      if (data.glueCCDResult01 !== undefined) {
        return 'glue' // 涂胶 类型
      }
      if (data.partLoadResult !== undefined) {
        return 'load' // 上料类型
      }

      if (data.partLoadResult !== undefined) {
        return 'load' // 上料类型
      }


      return 'default'
    },

    fieldConfig() {
      return getFieldConfig(this.detectedDataType)
    },

    groupedFields() {
      const fields = this.getVisibleFields()

      // 如果未启用分组，使用原始的简单分组方式
      if (!this.enableGrouping) {
        const grouped = []
        for (let i = 0; i < fields.length; i += this.fieldsPerRow) {
          grouped.push(fields.slice(i, i + this.fieldsPerRow))
        }
        return grouped
      }

      // 按后缀分组
      const groupedByNumber = this.groupFieldsByNumber(fields)

      // 将分组后的字段重新组织成行
      const grouped = []

      // 遍历每个数字分组
      Object.keys(groupedByNumber).sort((a, b) => {
        // 特殊处理：无后缀的字段排在最前面
        if (a === 'none') return -1
        if (b === 'none') return 1
        return parseInt(a) - parseInt(b)
      }).forEach(numberSuffix => {
        const groupFields = groupedByNumber[numberSuffix]

        // 为每个分组添加分组信息
        const groupInfo = {
          isGroupHeader: true,
          numberSuffix,
          colorClass: this.getGroupColorClass(numberSuffix),
          groupName: this.getGroupName(numberSuffix)
        }

        // 添加分组标题行
        if (numberSuffix !== 'none' && groupFields.length > 0) {
          grouped.push([groupInfo])
        }

        // 将该分组的字段按行分割
        for (let i = 0; i < groupFields.length; i += this.fieldsPerRow) {
          const rowFields = groupFields.slice(i, i + this.fieldsPerRow)
          // 为每个字段添加分组颜色信息
          rowFields.forEach(field => {
            field.groupColorClass = this.enableGrouping ? this.getGroupColorClass(numberSuffix) : ''
            field.numberSuffix = numberSuffix
          })
          grouped.push(rowFields)
        }
      })

      return grouped
    }
  },

  methods: {
    /**
     * 按数字后缀分组字段
     */
    groupFieldsByNumber(fields) {
      const groups = {}

      fields.forEach(field => {
        // 提取字段名中的数字后缀
        const numberMatch = field.key.match(/(\d+)$/)
        const numberSuffix = numberMatch ? numberMatch[1] : 'none'

        if (!groups[numberSuffix]) {
          groups[numberSuffix] = []
        }

        groups[numberSuffix].push(field)
      })

      // 对每个分组内的字段进行排序
      Object.keys(groups).forEach(suffix => {
        groups[suffix].sort((a, b) => a.order - b.order)
      })

      return groups
    },

    /**
     * 获取分组颜色类名
     */
    getGroupColorClass(numberSuffix) {
      const colorMap = {
        'none': 'group-none',
        '01': 'group-01',
        '02': 'group-02',
        '03': 'group-03',
        '04': 'group-04',
        '05': 'group-05',
        '06': 'group-06',
        '07': 'group-07',
        '08': 'group-08',
        '09': 'group-09',
        '10': 'group-10',
        '11': 'group-11',
        '12': 'group-12'
      }

      return colorMap[numberSuffix] || 'group-default'
    },

    /**
     * 获取分组名称
     */
    getGroupName(numberSuffix) {
      if (numberSuffix === 'none') {
        return '基础信息'
      }

      // 根据数据类型和后缀生成更有意义的分组名称
      const dataType = this.detectedDataType

      if (dataType === 'screw') {
        const screwNameMap = {
          '01': '1#螺丝相关参数',
          '02': '2#螺丝相关参数',
          '03': '3#螺丝相关参数',
          '04': '4#螺丝相关参数',
          '05': '5#螺丝相关参数',
          '06': '6#螺丝相关参数',
          '07': '7#螺丝相关参数',
          '08': '8#螺丝相关参数',
          '09': '9#螺丝相关参数',
          '10': '10#螺丝相关参数',
          '11': '11#螺丝相关参数',
          '12': '12#螺丝相关参数'
        }
        return screwNameMap[numberSuffix] || `${numberSuffix}#螺丝相关参数`
      }

      if (dataType === 'resistance') {
        const resistanceNameMap = {
          '01': '安全接地1测试参数',
          '02': '安全接地2测试参数',
          '03': '安全接地3测试参数'
        }
        return resistanceNameMap[numberSuffix] || `测试参数组${numberSuffix}`
      }

      if (dataType === 'camera') {
        const cameraNameMap = {
          '01': '1#相机检测参数',
          '02': '2#相机检测参数',
          '03': '3#相机检测参数'
        }
        return cameraNameMap[numberSuffix] || `${numberSuffix}#相机检测参数`
      }

      if (dataType === 'glue') {
        const glueNameMap = {
          '01': '壳体',
          '02': '主控板盖板',
          '03': '三相盖板',
          '04': '低压线束盖板',
          '05': '母线盖板'
        }
        return glueNameMap[numberSuffix] || `${numberSuffix}#涂胶检测参数`
      }

      // 默认分组名称
      const defaultNameMap = {
        '01': '第1组参数',
        '02': '第2组参数',
        '03': '第3组参数',
        '04': '第4组参数',
        '05': '第5组参数',
        '06': '第6组参数',
        '07': '第7组参数',
        '08': '第8组参数',
        '09': '第9组参数',
        '10': '第10组参数',
        '11': '第11组参数',
        '12': '第12组参数'
      }

      return defaultNameMap[numberSuffix] || `第${numberSuffix}组参数`
    },

    getVisibleFields() {
      const data = this.parsedData
      const config = this.fieldConfig
      const fields = []

      // 遍历数据中的所有字段
      Object.keys(data).forEach(key => {
        const value = data[key]

        // 跳过null、undefined或空字符串的字段（可选）
        if (value === null || value === undefined || value === '') {
          return
        }

        // 获取字段配置
        const fieldConfig = config.fields[key] || {}

        // 如果字段被明确隐藏，则跳过
        if (fieldConfig.hidden) {
          return
        }

        fields.push({
          key,
          label: fieldConfig.label || mapFieldName(key),
          type: fieldConfig.type || 'text',
          format: fieldConfig.format,
          span: fieldConfig.span || 8,
          order: fieldConfig.order || 999
        })
      })

      // 按order排序
      fields.sort((a, b) => a.order - b.order)

      return fields
    },

    formatValue(field, value) {
      if (value === null || value === undefined) {
        return '-'
      }

      // 处理字节数组
      if (Array.isArray(value) && field.type === 'bytes') {
        return this.bytesToString(value)
      }

      // 根据字段类型格式化
      switch (field.type) {
        case 'result':
          return this.formatResult(value)
        case 'number':
          return this.formatNumber(value, field.format)
        case 'percentage':
          return `${value}%`
        case 'unit':
          return `${value}${field.format?.unit || ''}`
        default:
          return String(value)
      }
    },

    formatResult(value) {
      // 结果状态映射
      const resultMap = {
        0: '未生产',
        1: '成功',
        2: 'NG'
      }
      return resultMap[value] || value
    },

    formatNumber(value, format) {
      if (!format) return value

      const num = parseFloat(value)
      if (isNaN(num)) return value

      if (format.decimals !== undefined) {
        return num.toFixed(format.decimals)
      }

      return num.toString()
    },

    bytesToString(bytes) {
      if (!Array.isArray(bytes)) return ''

      // 过滤掉0值，转换为字符串
      const validBytes = bytes.filter(b => b !== 0)
      return String.fromCharCode(...validBytes).trim()
    },

    getValueClass(field, value) {
      const classes = ['field-value']

      if (field.type === 'result') {
        if (value === 1) {
          classes.push('success')
        } else if (value === 0) {
          classes.push('error')
        } else if (value === 2) {
          classes.push('warning')
        }
      }

      return classes
    }
  }
}
</script>

<style scoped>
.detail-row {
  margin-bottom: 15px;
}

.grid-content {
  padding: 8px 12px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border-left: 3px solid #409eff;
  transition: all 0.3s ease;
}

.field-label {
  font-weight: 600;
  color: #606266;
  margin-right: 8px;
}

.field-value {
  color: #303133;
}

.field-value.success {
  color: #67c23a;
  font-weight: 600;
}

.field-value.error {
  color: #f56c6c;
  font-weight: 600;
}

.field-value.warning {
  color: #e6a23c;
  font-weight: 600;
}

.no-data {
  text-align: center;
  padding: 40px 0;
}

/* 分组标题样式 */
.group-header {
  margin: 20px 0 15px 0;
}

.group-title {
  font-weight: 600;
  font-size: 14px;
  padding: 0 15px;
}

/* 分组颜色样式 */
.group-none .grid-content {
  background-color: #f8f9fa;
  border-left-color: #909399;
}

.group-01 .grid-content,
.group-title.group-01 {
  background-color: #e8f4fd;
  border-left-color: #409eff;
  color: #409eff;
}

.group-02 .grid-content,
.group-title.group-02 {
  background-color: #f0f9ff;
  border-left-color: #67c23a;
  color: #67c23a;
}

.group-03 .grid-content,
.group-title.group-03 {
  background-color: #fdf6ec;
  border-left-color: #e6a23c;
  color: #e6a23c;
}

.group-04 .grid-content,
.group-title.group-04 {
  background-color: #fef0f0;
  border-left-color: #f56c6c;
  color: #f56c6c;
}

.group-05 .grid-content,
.group-title.group-05 {
  background-color: #f4f4f5;
  border-left-color: #909399;
  color: #909399;
}

.group-06 .grid-content,
.group-title.group-06 {
  background-color: #f2f6fc;
  border-left-color: #c0c4cc;
  color: #c0c4cc;
}

.group-07 .grid-content,
.group-title.group-07 {
  background-color: #fdf2ec;
  border-left-color: #e6a23c;
  color: #e6a23c;
}

.group-08 .grid-content,
.group-title.group-08 {
  background-color: #f0f2f5;
  border-left-color: #606266;
  color: #00d2ce;
}
.group-09 .grid-content,
.group-title.group-08 {
  background-color: #f0f2f5;
  border-left-color: #606266;
  color: #db00a4;
}
.group-10 .grid-content,
.group-title.group-08 {
  background-color: #f0f2f5;
  border-left-color: #606266;
  color: #8edb00;
}
.group-11 .grid-content,
.group-title.group-08 {
  background-color: #f0f2f5;
  border-left-color: #606266;
  color: #db8300;
}

.group-12 .grid-content,
.group-title.group-08 {
  background-color: #f0f2f5;
  border-left-color: #606266;
  color: #db003e;
}

.group-default .grid-content,
.group-title.group-default {
  background-color: #f8f9fa;
  border-left-color: #dcdfe6;
  color: #606266;
}

/* 分组内字段标签颜色调整 */
.group-01 .field-label { color: #337ecc; }
.group-02 .field-label { color: #529b2e; }
.group-03 .field-label { color: #b88230; }
.group-04 .field-label { color: #c45656; }
.group-05 .field-label { color: #73767a; }
.group-06 .field-label { color: #a6a9ad; }
.group-07 .field-label { color: #b88230; }
.group-08 .field-label { color: #4c4e52; }
.group-09 .field-label { color: #1161ff; }
.group-10 .field-label { color: #ff62c8; }
.group-11 .field-label { color: #749f00; }
.group-12 .field-label { color: #ff6b6b; }

/* 悬停效果 */
.grid-content:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 分组标题图标 */
.group-title i {
  margin-right: 5px;
}
</style>
